import db from '../config/database.js';
import { generatePatientCode } from '../utils/crypto.js';
import { callInferenceService } from '../services/aiInferenceService.js';
import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.simple()
    })
  ]
});

// 提交评分任务
export const submitTask = async (req, res) => {
  let connection;
  try {
    // 添加安全检查，确保req.user存在
    if (!req.user || !req.user.doctor_id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证或认证信息无效',
        data: null
      });
    }

    const { patient_code, clinical_text } = req.body;
    const { doctor_id } = req.user;
    const imageFile = req.file;

    // 参数验证
    if (!imageFile) {
      return res.status(400).json({
        success: false,
        message: '请上传内镜图像',
        data: null
      });
    }

    if (!patient_code || !patient_code.trim()) {
      return res.status(400).json({
        success: false,
        message: '患者编号不能为空',
        data: null
      });
    }

    logger.info('提交评分任务:', {
      doctor_id,
      patient_code,
      clinical_text: clinical_text?.substring(0, 100),
      image_filename: imageFile.filename,
      image_size: imageFile.size
    });

    // 使用事务处理
    const result = await db.transaction(async (conn) => {
      // 1. 查找或创建患者
      const patients = await conn.query(
        'SELECT patient_id FROM patients WHERE patient_code = ?',
        [patient_code.trim()]
      );

      let patient_id;
      if (patients.length === 0) {
        // 创建新患者
        const insertResult = await conn.query(
          'INSERT INTO patients (patient_code) VALUES (?)',
          [patient_code.trim()]
        );
        patient_id = insertResult[0]?.insertId;
        logger.info('创建新患者:', { patient_id, patient_code: patient_code.trim() });
      } else {
        patient_id = patients[0].patient_id;
        logger.info('使用现有患者:', { patient_id, patient_code: patient_code.trim() });
      }

      // 2. 创建评分任务（状态设置为"分析中"）
      const taskResult = await conn.query(`
        INSERT INTO scoring_tasks (patient_id, doctor_id, status, submit_time, image_url, clinical_text)
        VALUES (?, ?, 2, datetime('now'), ?, ?)
      `, [
        patient_id,
        doctor_id,
        `/uploads/medical_images/${imageFile.filename}`,
        clinical_text || null
      ]);

      const task_id = taskResult[0]?.insertId;

      logger.info('评分任务创建成功:', { task_id, patient_id, doctor_id });

      return { task_id, patient_id, imagePath: `/uploads/medical_images/${imageFile.filename}` };
    });

    // 3. 立即返回202 Accepted响应
    res.status(202).json({
      success: true,
      message: '任务已提交，正在进行分析中...',
      data: {
        task_id: result.task_id || 'pending',
        status: 2, // 分析中
        message: 'AI分析正在进行中，请稍后查看结果',
        patient_code: patient_code.trim(),
        image_path: result.imagePath
      }
    });

    // 4. 在后台触发AI推理服务（无等待）- 修复版本
    setImmediate(() => {
      const fullPath = `d:/VSCodeProjects/UC_System${result.imagePath}`;
      logger.info('开始后台AI推理调用:', { task_id: result.task_id, imagePath: fullPath });
      
      callInferenceService(result.task_id, fullPath)
        .then(() => {
          logger.info('后台AI推理调用成功:', { task_id: result.task_id });
        })
        .catch(error => {
          logger.error('后台AI推理调用失败:', { 
            task_id: result.task_id, 
            error: error.message,
            stack: error.stack 
          });
        });
    });

  } catch (error) {
    logger.error('提交评分任务失败:', error);
    res.status(500).json({
      success: false,
      message: '任务提交失败，请稍后重试',
      data: null
    });
  }
};


// 获取严重程度名称
const getSeverityName = (severity) => {
  const severityMap = {
    1: '缓解期',
    2: '轻度',
    3: '中度',
    4: '重度'
  };
  return severityMap[severity] || '未知';
};

// 获取评分任务列表
export const getTaskList = async (req, res) => {
  try {
    // 添加安全检查，确保req.user存在
    if (!req.user || !req.user.doctor_id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证或认证信息无效',
        data: null
      });
    }

    const { page = 1, pageSize = 10, patient_code, status } = req.body;
    const { doctor_id, role } = req.user;

    const offset = (page - 1) * pageSize;

    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];

    // TDP-001: 添加调试日志
    logger.info(`[getTaskList] 查询参数:`, { page, pageSize, patient_code, status, doctor_id, role });

    // 非系统管理员只能查看自己提交的任务
    if (role !== 3) {
      whereConditions.push('st.doctor_id = ?');
      queryParams.push(doctor_id);
    }

    if (patient_code && patient_code.trim()) {
      whereConditions.push('p.patient_code LIKE ?');
      queryParams.push(`%${patient_code.trim()}%`);
    }

    // TDP-001: 临时修改 - 显示所有状态的任务以便调试
    // 如果没有指定状态，默认显示所有状态（包括分析中的任务）
    if (status !== undefined && status !== null && status !== '') {
      whereConditions.push('st.status = ?');
      queryParams.push(parseInt(status));
    } else {
      // 临时：如果没有指定状态，显示所有状态的任务（1,2,3,4）
      logger.info(`[getTaskList] 未指定状态，显示所有状态的任务以便调试`);
    }

    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';

    // TDP-001: 添加查询SQL调试日志
    const debugSQL = `
      SELECT
        st.task_id,
        st.patient_id,
        st.doctor_id,
        st.status,
        st.submit_time,
        st.complete_time,
        p.patient_code,
        d.real_name as doctor_name,
        d.department,
        sr.score,
        sr.severity,
        sr.confidence,
        sr.analysis_details
      FROM scoring_tasks st
      LEFT JOIN patients p ON st.patient_id = p.patient_id
      LEFT JOIN doctors d ON st.doctor_id = d.doctor_id
      LEFT JOIN scoring_results sr ON st.task_id = sr.task_id
      ${whereClause}
      ORDER BY st.submit_time DESC
      LIMIT ? OFFSET ?
    `;
    logger.info(`[getTaskList] 执行查询SQL:`, { SQL: debugSQL, params: [...queryParams, parseInt(pageSize), offset] });

    // 查询任务列表
    const [tasks] = await db.query(`
      SELECT
        st.task_id,
        st.patient_id,
        st.doctor_id,
        st.status,
        st.submit_time,
        st.complete_time,
        p.patient_code,
        d.real_name as doctor_name,
        d.department,
        sr.score,
        sr.severity,
        sr.confidence,
        sr.analysis_details
      FROM scoring_tasks st
      LEFT JOIN patients p ON st.patient_id = p.patient_id
      LEFT JOIN doctors d ON st.doctor_id = d.doctor_id
      LEFT JOIN scoring_results sr ON st.task_id = sr.task_id
      ${whereClause}
      ORDER BY st.submit_time DESC
      LIMIT ? OFFSET ?
    `, [...queryParams, parseInt(pageSize), offset]);

    // 查询总数
    const [countResult] = await db.query(`
      SELECT COUNT(*) as total
      FROM scoring_tasks st
      LEFT JOIN patients p ON st.patient_id = p.patient_id
      ${whereClause}
    `, queryParams);

    const total = countResult?.[0]?.total || countResult?.total || 0;

    // 格式化任务数据
    const formattedTasks = (tasks || []).map(task => ({
      task_id: task.task_id,
      patient_code: task.patient_code,
      doctor_name: task.doctor_name,
      department: task.department,
      status: task.status,
      status_name: getStatusName(task.status),
      submit_time: task.submit_time,
      complete_time: task.complete_time,
      score: task.score,
      severity: task.severity,
      severity_name: getSeverityName(task.severity),
      confidence: task.confidence,
      analysis_details: task.analysis_details
    }));

    res.json({
      success: true,
      message: '获取任务列表成功',
      data: {
        items: formattedTasks,
        pagination: {
          current_page: parseInt(page),
          page_size: parseInt(pageSize),
          total: total,
          total_pages: Math.ceil(total / pageSize)
        }
      }
    });

  } catch (error) {
    logger.error('获取任务列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取任务列表失败',
      data: null
    });
  }
};

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    1: '待处理',
    2: '分析中',
    3: '已完成',
    4: '失败'
  };
  return statusMap[status] || '未知';
};

// 获取单个评分结果
export const getTaskResult = async (req, res) => {
  try {
    // 添加安全检查，确保req.user存在
    if (!req.user || !req.user.doctor_id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证或认证信息无效',
        data: null
      });
    }

    // 支持POST（从body获取）和GET（从params获取）两种方式
    const task_id = req.body.task_id || req.params.taskId || req.params.task_id;
    const { doctor_id, role } = req.user;

    if (!task_id) {
      return res.status(400).json({
        success: false,
        message: '任务ID不能为空',
        data: null
      });
    }

    // 查询任务详情和结果
    const queryResult = await db.query(`
      SELECT
        st.task_id,
        st.patient_id,
        st.doctor_id,
        st.status,
        st.submit_time,
        st.complete_time,
        st.image_url,
        st.clinical_text,
        p.patient_code,
        p.gender,
        p.birthday,
        d.real_name as doctor_name,
        d.department,
        d.title,
        sr.score,
        sr.severity,
        sr.confidence,
        sr.model_version,
        sr.analysis_details,
        sr.reviewed_score,
        sr.reviewed_notes
      FROM scoring_tasks st
      LEFT JOIN patients p ON st.patient_id = p.patient_id
      LEFT JOIN doctors d ON st.doctor_id = d.doctor_id
      LEFT JOIN scoring_results sr ON st.task_id = sr.task_id
      WHERE st.task_id = ?
      ${role !== 3 ? 'AND st.doctor_id = ?' : ''}
    `, role !== 3 ? [task_id, doctor_id] : [task_id]);

    const tasks = queryResult || [];

    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在或无权访问',
        data: null
      });
    }

    const task = tasks[0];

    // 格式化返回数据
    const result = {
      task_id: task.task_id,
      patient: {
        patient_id: task.patient_id,
        patient_code: task.patient_code,
        gender: task.gender,
        gender_name: getGenderName(task.gender),
        birthday: task.birthday
      },
      doctor: {
        doctor_id: task.doctor_id,
        real_name: task.doctor_name,
        department: task.department,
        title: task.title
      },
      task_info: {
        status: task.status,
        status_name: getStatusName(task.status),
        submit_time: task.submit_time,
        complete_time: task.complete_time,
        image_url: task.image_url,
        clinical_text: task.clinical_text
      },
      ai_result: task.score ? {
        score: task.score,
        severity: task.severity,
        severity_name: getSeverityName(task.severity),
        confidence: task.confidence,
        model_version: task.model_version,
        analysis_details: task.analysis_details
      } : null,
      review_result: task.reviewed_score ? {
        reviewed_score: task.reviewed_score,
        reviewed_notes: task.reviewed_notes
      } : null
    };

    res.json({
      success: true,
      message: '获取任务结果成功',
      data: result
    });

  } catch (error) {
    logger.error('获取任务结果失败:', error);
    res.status(500).json({
      success: false,
      message: '获取任务结果失败',
      data: null
    });
  }
};

// 获取性别名称
const getGenderName = (gender) => {
  const genderMap = {
    0: '未知',
    1: '男',
    2: '女'
  };
  return genderMap[gender] || '未知';
};